package com.huawei.virest.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class FileDownloadServlet extends HttpServlet
{

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        saveRequest(request, response);// 保存请求文件
    }

	/**
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
    @SuppressWarnings("unchecked")
	private void saveRequest(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException,
			IOException {
		String method = "";
        String value = "";
        String key = "";
        String body = "";
        String url = "";
        String keyTwo ="";
        String valueTwo = "";
        DiskFileItemFactory diff = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(diff);

        try
        {
            List items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();)
            {
                FileItem fileItem = (FileItem) i.next();
                if (fileItem.isFormField())
                {
                    String field = fileItem.getFieldName();
                    if (field.equals("method"))
                    {
                        method = fileItem.getString();
                    }
                    else if (field.equals("key"))
                    {
                        key = fileItem.getString();
                    }
                    else if (field.equals("value"))
                    {
                        value = fileItem.getString();
                        value = value.replaceAll("\"", "&quot;");
                    }
                    else if (field.equals("url"))
                    {
                        url = fileItem.getString();
                    }
                    else if (field.equals("body"))
                    {
                        body = fileItem.getString("utf-8");
                    }
                    else if(field.equals("keyTwo"))
                    {
                        keyTwo = fileItem.getString();
                    }
                    else if(field.equals("valueTwo"))
                    {
                        valueTwo =fileItem.getString();
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        StringBuffer buff = new StringBuffer();
        System.out.println(body.trim());
        String head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rest-client version=\"2.3\"><request><http-version>1.1</http-version><URL>";
        buff.append(head).append(url).append("</URL><method>").append(method).append(
                "</method><headers><header key=\"").append(key).append("\" value=\"").append(value).append("\"/>");
        if(null != keyTwo&& null != valueTwo)
        {
            buff.append("<header key=\"").append(keyTwo).append("\" value=\"").append(valueTwo).append("\"/>")
            .append("</headers><body content-type=\"text/plain\" charset=\"UTF-8\">");
        }
        else
        {
            buff.append("</headers><body content-type=\"text/plain\" charset=\"UTF-8\">");
        }
        
        if (null != body)
        {
            buff.append(body).append("</body><test-script></test-script></request></rest-client>");
        }
        else
        {
            buff.append("</body>");
        }
        response.setHeader("Content-disposition", "attachment;filename=\"" + URLEncoder.encode(".rcq","UTF-8"));
        response.setContentType("application/text;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        out.write(buff.toString().getBytes("UTF-8"));
        out.flush();
        out.close();
	}
}
